package com.totoro.author.aop ;

import javax.servlet.http.HttpServletRequest ;

import org.aspectj.lang.JoinPoint ;
import org.aspectj.lang.annotation.Aspect ;
import org.aspectj.lang.annotation.Before ;
import org.aspectj.lang.annotation.Pointcut ;
import org.springframework.beans.factory.annotation.Autowired ;
import org.springframework.stereotype.Component ;

import com.totoro.author.author.Access ;
import com.totoro.author.author.CommonIdentifier ;
import com.totoro.author.exception.ExceptionType ;
import com.totoro.author.exception.NoAuthorToJsonException ;
import com.totoro.author.exception.NoAuthorToPageException ;

/**
 * 处理@Access注解的aop
 * @author 80002165 @date 2017年8月2日 上午10:44:56
 */
@Component
@Aspect
public class AuthorAOP {
    @Autowired
    private HttpServletRequest request ;
    
    // 1、定义一个切点
    @Pointcut("@annotation(com.totoro.author.author.Access)")
    public void accessPointCut() {
    }
    
    // 2、定义处理切面事件
    @Before("accessPointCut() && @annotation(access)")
    public void accessAuthor(JoinPoint joinPoint, Access access) {
        CommonIdentifier author = access.author() ;
        ExceptionType result = access.result() ;
        if (author != null) {
            boolean hasAuthor = author.identify(request.getSession()) ;
            if (!hasAuthor) {
                if (ExceptionType.JSON == result)
                    throw new NoAuthorToJsonException() ;
                else if (ExceptionType.PAGE == result)
                    throw new NoAuthorToPageException() ;
            }
        }
    }
    
}
